package transcoding

import org.codehaus.jackson.annotate.JsonAutoDetect
import org.codehaus.jackson.annotate.JsonProperty
import org.codehaus.jackson.annotate.JsonMethod
import com.xuggle.xuggler.IContainerFormat

import scala.annotation.target.field

@JsonAutoDetect(Array(JsonMethod.NONE))
class MediaFileManager(@(JsonProperty @field) val mainMediaFile: MediaFile) {

  @JsonProperty("title")
  val fileName = new java.io.File(mainMediaFile.filePath).getName

  private var otherVersions_ = scala.collection.mutable.IndexedSeq[MediaFile]()

  @JsonProperty
  def otherVersions = otherVersions_.synchronized(otherVersions_)

  def addOtherVersion(mediaFile: MediaFile) = {
    otherVersions_.synchronized {
        val idx = otherVersions_.indexOf(mediaFile)
        if (idx < 0) otherVersions_ = otherVersions_ :+ mediaFile
        else otherVersions_ = otherVersions_ updated(idx, mediaFile)
    }
  }

  def getMediaFileWithMaxBitRateAndFormat(maxBitRate: Option[Int], format: Option[IContainerFormat], player: Player) = {
    if ((player supports mainMediaFile) && mainMediaFile.bitRate.getOrElse(0) <= maxBitRate.getOrElse(Int.MaxValue) &&
      mainMediaFile.format.map(informat => informat.getInputFormatShortName.equals(format.getOrElse(informat).getInputFormatShortName))
      .getOrElse(false))

      Some(mainMediaFile)
    else
      otherVersions.filter(mf => mf.bitRate.isDefined && mf.bitRate.get <= maxBitRate.getOrElse(Int.MaxValue))
        .sortWith((m1, m2) => m1.bitRate.get >= m2.bitRate.get)
        .filter(mf =>
          (player supports mf) &&
            mf.format.get.getInputFormatShortName == format.getOrElse(mf.format.get).getInputFormatShortName)
        .headOption
  }

  def getMediaFileWithFormat(format: IContainerFormat, player: Player) = {
    getMediaFileWithMaxBitRateAndFormat(None, Some(format), player)
  }

  def getMediaFileWithMaxBitRate(maxBitRate: Int, player: Player) = {
    getMediaFileWithMaxBitRateAndFormat(Some(maxBitRate), None, player)
  }
}